// 导入了名为com.larissa.android.quiz的包
package com.zekai.calculator;
// 导入了AppCompatActivity类，这是Android应用的基础活动类


import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.MenuProvider;
import androidx.lifecycle.ViewModelProvider;

import com.zekai.calculator.databinding.ActivityMainBinding;



// 定义了一个公共类，类名为MainActivity，继承自AppCompatActivity类
public class MainActivity extends AppCompatActivity {



    private Button[] standardButtons;
    private Button[] scientificButtons;
    //可变运算符初始化
    private Button btn_ln;
    private Button btn_log;
    private Button btn_sin;
    private Button btn_cos;
    private Button btn_tan;
    private Button btn_RAD;



    //状态框
    // state
    private TextView tv_state;
    // M
    private TextView tv_Memory;
    //  输入框
    private EditText tv_input;
    //  结果框
    private TextView tv_result;
    //反函数标识，false表示不是反函数，true表示是反函数
    Boolean inv_flag=false;
    //  清空标识,false表示不清空，true表示清空
    //RAD标识，false表示角度制，true表示弧度制

    Boolean clear_flag=false;

    String memoryResult;


    //tag
    private static final String TAG="Calculator-MainActivity";
    //  运算结果
    private String FinalResult;
    private String input;
    private MainViewModel viewModel;
    private MainMenu menu;
    //历史记录
    private HistoryRepository historyRepository;



    //点击事件
    //输入
    public void onClick(View v) {
        viewModel.expression=tv_input.getText().toString();

        if(viewModel.result!=null){
            viewModel.result="";
            tv_result.setText(viewModel.result);
        }

        int viewId = v.getId();
        //打印viewId对应的text
//        Log.d(TAG,((Button) v).getText().toString());
        //如果输入框为空或者最后一个字符是'('，则不可以输入运算符+,*,/,
        if (viewModel.expression == null || viewModel.expression.equals("")||viewModel.expression.endsWith("(")) {
            if (viewId == R.id.btn_add ||
                    viewId == R.id.btn_multiply ||
                    viewId == R.id.btn_divide
                    ) {
                return;
            }
        }
        //不能连续输入两个dot
        if(viewId==R.id.btn_dot){
            if(viewModel.expression.endsWith(".")){
                return;
            }
        }
        //如果连续输入两个运算符，第二个运算符替换第一个运算符
        if(viewId==R.id.btn_add ||
                viewId==R.id.btn_multiply ||
                viewId==R.id.btn_divide){
            if(viewModel.expression.endsWith("+") ||
                    viewModel.expression.endsWith("-") ||
                    viewModel.expression.endsWith("*") ||
                    viewModel.expression.endsWith("/")){
                tv_input.setText(viewModel.expression.substring(0,viewModel.expression.length()-1)+((Button) v).getText());
                return;
            }
        }
        //如果最后一个是加号或者减号，将其替换成减号
        if(viewId==R.id.btn_minus){
            if(viewModel.expression.endsWith("+")||viewModel.expression.endsWith("-")){
                tv_input.setText(viewModel.expression.substring(0,viewModel.expression.length()-1)+((Button) v).getText());
                return;
            }
        }


        //如果输入框最后一个是括号，输入框不变，结果框显示错误
        if(viewId==R.id.right_bracket){
            //如果str最后是运算符，输入框不变，结果框显示错误
            if(viewModel.expression.endsWith("+") ||
                    viewModel.expression.endsWith("-") ||
                    viewModel.expression.endsWith("*") ||
                    viewModel.expression.endsWith("/")||
                    viewModel.expression.endsWith(".")){
//                viewModel.result="错误";
                viewModel.expression+=")";
                tv_input.setText(viewModel.expression);
                viewModel.result="错误";
                tv_result.setText(viewModel.result);
                return;
            }
        }




        //如果是数字或者小数点或者是e,π
        if (viewId == R.id.num_0 ||
                viewId == R.id.num_1 ||
                viewId == R.id.num_2 ||
                viewId == R.id.num_3 ||
                viewId == R.id.num_4 ||
                viewId == R.id.num_5 ||
                viewId == R.id.num_6 ||
                viewId == R.id.num_7 ||
                viewId == R.id.num_8 ||
                viewId == R.id.num_9 ||
                viewId == R.id.btn_dot||
                viewId == R.id.euler||
                viewId == R.id.pi) {
            // 如果清空了输入框，则将输入框清空标识设置为false
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            // 将输入框中的内容与按钮的内容拼接起来
            tv_input.setText(viewModel.expression + ((Button) v).getText());
        }
        //如果是括号
        else if (viewId == R.id.left_bracket ||
                viewId == R.id.right_bracket) {
            // 如果清空了输入框，则将输入框清空标识设置为false
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            // 将输入框中的内容与按钮的内容拼接起来
            tv_input.setText(viewModel.expression + ((Button) v).getText());
        }
        // 如果是简单运算符：加减乘除%,
        else if (viewId == R.id.btn_add ||
                viewId == R.id.btn_minus ||
                viewId == R.id.btn_multiply ||
                viewId == R.id.btn_divide||
                viewId == R.id.percent) {
            // 处理加减乘除的情况
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            tv_input.setText(viewModel.expression + ((Button) v).getText());
        }
        // 如果是倒数
        else if (viewId == R.id.reciprocal) {
            // 处理倒数的情况
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            tv_input.setText(viewModel.expression + "^(-1)");
        }
        //如果是平方sqr
        else if (viewId == R.id.sqr) {
            // 处理平方的情况
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            tv_input.setText(viewModel.expression + "^(2)");
        }
        //如果是立方cube
        else if (viewId == R.id.cube) {
            // 处理立方的情况
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            tv_input.setText(viewModel.expression + "^(3)");
        }
        //如果是乘幂power
        else if (viewId == R.id.power) {
            // 处理乘幂的情况
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            tv_input.setText(viewModel.expression + "^(");
        }
        //如果是阶乘factorial
        else if (viewId == R.id.factorial) {
            // 处理阶乘的情况
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            tv_input.setText(viewModel.expression + "!");
        }
        //如果是平方根sqrt
        else if (viewId == R.id.square_root) {
            // 处理平方根的情况
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            tv_input.setText(viewModel.expression + "√");
        }
        //如果是开方powerRoot
        else if (viewId == R.id.power_root) {
            // 处理开方的情况
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            tv_input.setText(viewModel.expression + "^(1/");
        }
        //如果是ln，log，sin，cos，tan
        else if(viewId==R.id.ln||
                viewId==R.id.log||
                viewId==R.id.sin||
                viewId==R.id.cos||
                viewId==R.id.tan) {
            // 处理ln,log,sin,cos,tan的情况
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            //处理有inv的情况
            //如果inv_flag为true，说明是反函数,先把按钮内的文字替换成反函数
            if(inv_flag){
                if(viewId==R.id.ln){
                    tv_input.setText(viewModel.expression + "e^(");
                }
                else if(viewId==R.id.log) {
                    tv_input.setText(viewModel.expression + "10^(");
                }
                else if(viewId==R.id.sin) {
                    tv_input.setText(viewModel.expression + "arcsin(");
                }
                else if(viewId==R.id.cos) {
                    tv_input.setText(viewModel.expression + "arccos(");
                }
                else if(viewId==R.id.tan) {
                    tv_input.setText(viewModel.expression + "arctan(");
                }
            }else {
                tv_input.setText(viewModel.expression + ((Button) v).getText() + "(");
            }


        }else if (viewId == R.id.inverse) {
            //切换inv_flag
            inv_flag = !inv_flag;
            Log.d(TAG, "inv_flag: " + inv_flag);

            if (inv_flag) {
                btn_ln.setText(R.string.ln_inverse);
                btn_log.setText(R.string.log_inverse);
                btn_sin.setText(R.string.sin_inverse);
                btn_cos.setText(R.string.cos_inverse);
                btn_tan.setText(R.string.tan_inverse);
            }
            //如果inv_flag为false，说明不是反函数,先把按钮内的文字替换成正常函数
            else {
                btn_ln.setText(R.string.ln);
                btn_log.setText(R.string.log);
                btn_sin.setText(R.string.sin);
                btn_cos.setText(R.string.cos);
                btn_tan.setText(R.string.tan);
            }

        }
        //如果是RAD
        else if (viewId == R.id.Rad) {
            //切换RAD_flag
            viewModel.isRad = !viewModel.isRad;
            Log.d(TAG, "RAD_flag: " + viewModel.isRad);

            if (viewModel.isRad) {
                btn_RAD.setText(R.string.Deg);
                tv_state.setText(R.string.Rad);
            }
            //如果RAD_flag为false，说明是角度制,先把按钮内的文字替换成角度制
            else {
                btn_RAD.setText(R.string.Rad);
                tv_state.setText(R.string.Deg);
            }
        }
        if (viewId == R.id.MClear) {
            // 处理MC的情况
            viewModel.memory = 0.0;
            viewModel.isMemoryEmpty = true;
            viewModel.isMemoryError = false;
            tv_Memory.setText("");
        } else if (viewId == R.id.MAdd || viewId == R.id.MSub) {
            // 处理M+和M-的情况
            String memoryResult = Calculator.evaluateExpression(viewModel.expression);
            if(viewModel.isMemoryError==false){
                viewModel.isMemoryError = (memoryResult.equals("错误")||memoryResult.equals("error")) ?true: false;
            }
            if (!viewModel.isMemoryError) {
                viewModel.memory = (viewId == R.id.MAdd) ? viewModel.memory + Double.parseDouble(memoryResult) : viewModel.memory - Double.parseDouble(memoryResult);
                viewModel.isMemoryEmpty = false;
            } else {
                viewModel.memory = 0.0;
            }

            tv_Memory.setText("M");
        } else if (viewId == R.id.MR) {
            //
            if (!viewModel.isMemoryEmpty && !viewModel.isMemoryError) {
                tv_input.setText(viewModel.expression + viewModel.memory);
                viewModel.expression = tv_input.getText().toString();
            } else if (viewModel.isMemoryError) {
                tv_result.setText("错误");
                viewModel.result = "错误";
            }
        }






        // 如果是清空
        else if (viewId == R.id.btn_clear) {
            // 处理清空的情况
            clear_flag = false;
            viewModel.expression = "";
            viewModel.result = "";
            // 将输入框和结果框清空
            tv_input.setText("");
            tv_result.setText("");
        }
        // 如果是删除
        else if (viewId == R.id.btn_delete) {
            //如果清空了输入框，则将输入框清空标识设置为false
            if (clear_flag) {
                clear_flag = false;
                viewModel.expression = "";
                tv_input.setText("");
            }
            //如果输入框不为空
            else if (viewModel.expression != null && !viewModel.expression.equals("")) {
                tv_input.setText(viewModel.expression.substring(0, viewModel.expression.length() - 1));
            }
        }
        // 如果是=
        else if (viewId == R.id.btn_equal) {
            //获取运算结果
            Log.d(TAG,"expression: "+viewModel.expression);
            //如果没有内容，不做任何操作
            if(viewModel.expression==null||viewModel.expression.equals("")){
                return;
            }
            viewModel.result=Calculator.evaluateExpression(viewModel.expression);
            viewModel.addToHistory(viewModel.expression,'='+viewModel.result);
            //打印repository中的表达式和结果
            Log.d(TAG,"expression: "+historyRepository.getAllExpressions());
            Log.d(TAG,"result: "+historyRepository.getAllResults());
            historyRepository.addExpressionAndResult(viewModel.expression,viewModel.result);
            FinalResult=viewModel.result.toString();
            tv_result.setText(FinalResult);
        }

    }

    //重写onCreate()方法

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG,"onCreate() called");

        super.onCreate(savedInstanceState);
        historyRepository = HistoryRepository.getInstance();
        // 设置布局文件
        ActivityMainBinding binding=ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());



        //设置viewModel
        viewModel=new ViewModelProvider(this).get(MainViewModel.class);
        //把viewModel和Calculator绑定
        Calculator.setViewModel(viewModel);
        //把viewModel和HistoryActivity绑定
        HistoryActivity.setViewModel(viewModel);
        // 获取传递的表达式
        String receivedExpression = getIntent().getStringExtra("expression");
        // 如果传递了表达式，则将其显示在输入框中
        if (receivedExpression != null) {
            viewModel.expression=receivedExpression;
            viewModel.result="";
            binding.ShowText.setText(receivedExpression);

        }
        //接收完表达式后，清空传递的表达式
        getIntent().removeExtra("expression");


        menu=new MainMenu();
        addMenuProvider(menu);
        initializeButtons(binding);
        initializeTextViews(binding);



    }
    private void initializeButtons(ActivityMainBinding binding){
        //初始化按钮
        //标准计算器按钮
        standardButtons = new Button[]{
                binding.num0, binding.num1, binding.num2, binding.num3, binding.num4,
                binding.num5, binding.num6, binding.num7, binding.num8, binding.num9,
                binding.btnDot, binding.btnEqual, binding.btnAdd, binding.btnMinus,
                binding.btnMultiply, binding.btnDivide, binding.btnClear, binding.leftBracket,
                binding.rightBracket, binding.btnDelete
        };
        //为每个按钮添加点击事件
        for (Button btn : standardButtons) {
            btn.setOnClickListener(this::onClick);
        }
        //科学计算器按钮
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            scientificButtons = new Button[]{
                    binding.reciprocal, binding.MClear, binding.MAdd, binding.MSub, binding.MR,
                    binding.sqr, binding.cube, binding.power, binding.factorial, binding.squareRoot,
                    binding.powerRoot, binding.euler, binding.pi, binding.ln, binding.log, binding.sin,
                    binding.cos, binding.tan, binding.percent, binding.inverse, binding.Rad
            };
            //为每个按钮添加点击事件
            for (Button btn : scientificButtons) {
                btn.setOnClickListener(this::onClick);
            }
        };
        //为特殊的5个运算符初始化
        btn_ln=binding.ln;
        btn_log=binding.log;
        btn_sin=binding.sin;
        btn_cos=binding.cos;
        btn_tan=binding.tan;
        btn_RAD=binding.Rad;

    }
    private void initializeTextViews(ActivityMainBinding binding) {
        tv_input = binding.ShowText;
        tv_result = binding.resultText;
        tv_Memory = binding.StateMemory;

        tv_input.setText(viewModel.expression);
        tv_result.setText(viewModel.result);
        //横屏
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            tv_state = binding.State1;
            tv_state.setText(viewModel.isRad ? R.string.Rad : R.string.Deg);
            if(viewModel.isMemoryEmpty){
                tv_Memory.setText("");
            }
            else{
                tv_Memory.setText("M");
            }
        }


    }
    // 菜单
    private class MainMenu implements MenuProvider {
        // 解析Menu布局样式，将得到的Menu对象添加到menu对象上
        @Override
        public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
            menuInflater.inflate(R.menu.activity_main,menu);
        }

        @SuppressLint("NonConstantResourceId")
        @Override
        public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {

            if(menuItem.getItemId()==R.id.History){
                // 显示历史记录
                Log.d(TAG,"History");
                JumpToHistory();
                return true;
            }
            else{
                return false;
            }
    }




    }
    private final ActivityResultLauncher<Intent> helpLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == RESULT_OK) {
                    // 处理返回的结果
                    Intent data = result.getData();
                    if (data != null) {

                    }
                }
            }
    );
    private void JumpToHistory() {
        // 当点击历史记录菜单项时，跳转到HistoryActivity并传递历史记录数据
        Intent historyIntent = new Intent(this,HistoryActivity.class);
        helpLauncher.launch(historyIntent);

    }

    //
    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG,"onStart() called");
    }
    //
    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume() called");
    }
    //
    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"onPause() called");
    }
    //
    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG,"onStop() called");
    }
    //
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy() called");
        boolean finished=isFinishing();
        Log.d(TAG,String.format("finished: %s",finished));

    }
    //定义一个内部类MainMenu，实现MenuProvider接口












}

